<template>
	<view class="relative full-screen">
		<view style="z-index:0;position:absolute;left:0;right:0;top:0;height:395px;background-image:radial-gradient(circle at left top, #D8230A26 50%, transparent 50%);background-size:396px 396px;background-repeat:no-repeat;filter:blur(50px);"></view>
		<z-paging ref="paging" v-model="dataList" @query="queryList">
			<template #top>
				<uni-nav-bar ref="navBar" fixed statusBar :border="false" backgroundColor="transparent">
					<view v-if="orderTypeTabs.length" class="flex center w-full fs-16 font-bold">
						<text class="text-color-regular" @click.stop="showPopup">{{ getOrderName }}</text>
						<image v-if="orderTypeTabs.length > 1" class="ml-2 w-16 h-16 mt-2" src="@/static/svg/icon-arrow-bottom.svg"></image>
					</view>
				</uni-nav-bar>
				<uni-popup ref="popup" type="top">
					<view class="bg-white flex-col pt-90">
						<view v-for="(tab, i) in orderTypeTabs" :key="i">
							<view class="mt-20 mb-16 leading-22 text-center text-color-regular fs-16 font-medium" @click="onOrderTypeTabClick(tab)">
								{{tab.name}}
							</view>
							<view class="h-1 bg-default"></view>
						</view>
					</view>
				</uni-popup>
				<view v-if="currentOrderType === 3" class="flex p-16">
					<view v-for="(tab, i) in subOrderTypeTabs" :key="i" class="h-28 flex-1 flex-col justify-between item-center" :class="subOrderType===tab.code ? 'text-bold' : ''" :style="subOrderType===tab.code ? 'color: #FF2043;' : ''" @click="onSubOrderTypeClick(tab)">
						<text class="fs-16">{{tab.name}}</text>
						<image v-if="subOrderType===tab.code" class="w-15 h-3" src="@/static/svg/tab-indicate.svg"></image>
					</view>
				</view>
				<view class="mx-16 radius-8 bg-white px-16 py-4 h-38 flex item-center">
					<image class="w-20 h-20 mr-4 flex-shrink" src="@/static/svg/icon-search.svg"></image>
					<input v-model="queryParams.activeTitle" class="fs-12 flex-1" placeholder="搜商品名称" placeholder-class="c9" />
					<image v-if="queryParams.activeTitle" class="w-18 h-18 ml-4" src="@/static/svg/icon-input-clean.svg" @click="cleanSearch"></image>
					<view class="ml-12 flex-shrink fs-16 color-primary" @click="doSearch">搜索</view>
				</view>
				<scroll-view scroll-x class="order-status-tabs px-16 my-16" scroll-with-animation :scroll-left="scrollLeft">
					<view v-for="(tab,i) in orderStatusTabs" :key="i" class="tab-item" :class="currentOrderStatusTab===tab.code ? 'active text-color-regular fs-16 text-bold':'text-color-hint fs-15'" @click="onOrderStatusTabClick(tab, i)">
						<text>{{tab.name}}</text>
					</view>
				</scroll-view>
			</template>
			<view class="flex-col">
				<OrderListItem
					v-for="(item,i) in dataList"
					:key="i"
					:data="item"
					:viewOrderType="currentOrderType"
					@onOrderUdate="queryList(1)"
					@toShare="toShare"
					class="mx-16 mb-12 radius-12 overflow-hidden"
				/>
			</view>
			<template #empty>
				<view class="flex-col item-center">
					<image style="height:140px;" src="@/static/svg/order/empty-order.svg"></image>
					<text class="mt-4 fs-12">暂无相关订单～</text>
				</view>
			</template>
			<template #loadingMoreNoMore>
				<view :style="`height:calc(120px + ${safeAreaBottom}px);`">
					<view class="text-center text-color-hint fs-14">到底了～</view>
				</view>
			</template>
			<template #bottom>
				<!-- <view :style="`height:calc(60px + ${safeAreaBottom}px);`"></view> -->
			</template>
		</z-paging>
		<sign-up-success-dialog ref="signupSuccessDialog" />
		<share-activity v-if="showSharePopup" :id="sharedActiveId" :show="showSharePopup" :ext-params="sharedExtParams"
			:type="shareActivityType" :not-promotion-incentive="notPromotionIncentive" @onClose="showSharePopup = false"
			:options="shareActivityOptions" />
	</view>
</template>

<script setup name="Order">
	import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
	import {
		computed,
		onMounted,
		ref,
		unref,
		watch,
		getCurrentInstance
	} from 'vue'
	import {
		useUserStore
	} from '@/stores/modules/user.js'
	import {
		pageBuyOrderApi,
		pageSellOrderApi,
		pageAgentOrderApi,
	} from '@/api/order.js'
	import { getOrderSelectTypeApi, listFrontOrderStateApi } from '@/api/common.js'
	import OrderListItem from './components/OrderListItem.vue'
	import SignUpSuccessDialog from './components/sign-up-success-dialog/sign-up-success-dialog.vue'

	const props = defineProps({
		defaultOrderStatus: {
			type: [Number, String],
			default: ''
		}
	})
	const popup = ref(false)
	const showPopup = () => {
		popup.value && popup.value.open()
	}
	const close = () => {
		popup.value && popup.value.close()
	}

	const userStore = useUserStore()
	const instance = getCurrentInstance()

	const navBar = ref(null)

	const navBarHeight = computed(() => {
		const statusBarHeight = uni.getWindowInfo().statusBarHeight
		const navigationBarHeight = statusBarHeight + (navBar.value && navBar.value.height || 0)
		return navigationBarHeight
	})
	const safeAreaBottom = computed(() => {
		return uni.getSystemInfoSync().safeAreaInsets.bottom
	})
	
	const cleanSearch = () => {
		queryParams.value.activeTitle = ''
		doSearch()
	}
	
	const doSearch = () => {
		queryParams.value.pageNum = 1
		paging.value.reload()
	}
	
	// 订单类型
	const orderTypeTabs = ref([
		// { name: '我购买的订单', code: 1 },
		// { name: '我卖出的订单', code: 2 },
		// { name: '我分销的订单', code: 3 }
	])
	// 推广订单类型
	const subOrderTypeTabs = ref([
		{ name: '自推订单', code: 1 },
		{ name: '团队订单', code: 2 },
	])
	const currentOrderType = ref(1)
	const subOrderType = ref(1)
	const getOrderName = computed(() => {
		let arr = orderTypeTabs.value.filter((item) => item.code === currentOrderType.value)
		return arr[0].name
	})
	const onOrderTypeTabClick = (tab) => {
		if (tab.value !== currentOrderType.value) {
			currentOrderType.value = tab.code
			currentOrderStatusTab.value = ''
			queryParams.value.orderState = ''
			queryParams.value.pageNum = 1
			paging.value.reload()
		}
		close()
	}
	const onSubOrderTypeClick = (tab) => {
		if (tab.value !== subOrderType.value) {
			subOrderType.value = tab.code
			queryParams.value.pageNum = 1
			paging.value.reload()
		}
	}
	// 订单状态
	const orderStatusTabs = ref([
		{ name: '全部', code: '' }
	])
	const currentOrderStatusTab = ref(props.defaultOrderStatus)
	const scrollLeft = ref(0)
	const onOrderStatusTabClick = (tab, i) => {
		if (tab.code !== currentOrderStatusTab.value) {
			scrollLeft.value = i * 40
			currentOrderStatusTab.value = tab.code
			queryParams.value.orderState = tab.code
			queryParams.value.pageNum = 1
			paging.value.reload()
		}
	}
	
	const paging = ref(null)
	const dataList = ref([])
	const queryParams = ref({
		orderSelectType: '',
		activeTitle: '',
		subOrderType: 1,
		orderState: props.defaultOrderStatus, // 订单状态：1-待支付, 2-待核销, 3-核销中, 4-已取消, 5-已完成, 6-已关闭
		pageNum: 1,
		pageSize: 10,
	})
	const queryList = (pageNo, pageSize) => {
		queryParams.value.pageNum = pageNo || 1
		if (currentOrderType.value === 1) {
			queryParams.value.subOrderType = 1
			pageBuyOrderApi(unref(queryParams)).then(res => {
				paging.value.complete(res.list)
			})
		} else if (currentOrderType.value === 2) {
			queryParams.value.subOrderType = 1
			pageSellOrderApi(unref(queryParams)).then(res => {
				paging.value.complete(res.list)
			})
		} else if (currentOrderType.value === 3) {
			queryParams.value.subOrderType = subOrderType.value
			pageAgentOrderApi(unref(queryParams)).then(res => {
				paging.value.complete(res.list)
			})
		}
	}
	
	/**
	 * 进入后判断用户身份：
		①非经纪人且非策划人，仅显示我购买的订单（不显示tab）；
		②是策划人，但不是经纪人，显示”我购买的订单“、”我卖出的订单“；
		③是供货团，又是经纪人，显示3个订单类型；
	 */
	const getOrderSelectType = () => {
		getOrderSelectTypeApi().then(res => {
			orderTypeTabs.value = res.map(it => {
				if (!userStore.isLogin) {
					it.show = false
				} else if (it.code === 2) {
					it.show = userStore.isMerchant
				} else if (it.code === 3) {
					it.show = userStore.isAgent
				} else if (it.code === 1) {
					it.show = true
				}
				return it
			}).filter(it => it.show)
			getOrderState()
		})
	}
	
	const getOrderState = () => {
		listFrontOrderStateApi().then(res => {
			orderStatusTabs.value = orderStatusTabs.value.concat(res)
		})
	}
	
	const signupSuccessDialog = ref(null)
	const onSignUpSuccess = (data) => {
		console.log('报名成功', data)
		signupSuccessDialog.value.showDialog(data)
	}
	
	onMounted(() => {
		getOrderSelectType()
		uni.$on('signUpSuccess', onSignUpSuccess)
	})
	
	onShareAppMessage((options) => {
		console.log('邀请好友', options)
		const activityId = options.target.dataset.activityId;
		const target = dataList.value.find(item=>item.activeId===activityId);

		if (options.from === 'button' && options.target.dataset.extParams.channel==='inviteFrient2GroupBuy') {
			const url = '/pagesA/order/group-buy-detail';
			return {
				title: options.target.dataset.title,
				path: `${url}?id=${target?.id}&activeId=${activityId}&isDirectJoin=true&groupBuyOrderId=${options.target.dataset.extParams.groupBuyOrderId}`,
				imageUrl: options.target.dataset.filepath
			}
		}

		const url = target?.promotionType==='GROUP_BUY'
				?`/pagesB/activity/activity-group-buy`
				:`/pagesB/activity/activity`;
		const params = {};
		if(target.groupBuyOrderInfo.groupBuyOrderId){
			params.groupBuyOrderId = target.groupBuyOrderInfo.groupBuyOrderId;
		}
		const paramsArr = Object.keys(params).map(key=>`${key}=${params[key]}`);
		if(paramsArr.length){
			paramsArr.unshift('');
		}
		const paramsStr = paramsArr.join('&');
		return {
			title: options.target.dataset.title,
			path: `${url}?id=${activityId}&code=${options.target.dataset.shareCode}${paramsStr}`,
			imageUrl: options.target.dataset.filepath
		}
	})

	const showSharePopup = ref(false)
	const sharedExtParams = ref();
	const sharedActiveId = ref();
	const notPromotionIncentive = ref(false);
	const shareActivityType = ref('');
	const shareActivityOptions = ref({});
	const toShare = (value) => {
		console.log('toShare');
		shareActivityType.value = '';
		notPromotionIncentive.value = false;
		shareActivityOptions.value = {};
		if(value.type==='inviteFrient2GroupBuy'){
			notPromotionIncentive.value = true;
			sharedActiveId.value = value.data.activeId;
			sharedExtParams.value = {
				groupBuyOrderId: value.data.groupBuyOrderInfo.groupBuyOrderId,
				channel:'inviteFrient2GroupBuy'
			};
			shareActivityType.value = 'inviteGroupBuy';
			shareActivityOptions.value = {groupBuyLabel:value.data.groupBuyOrderInfo ? `${value.data.groupBuyOrderInfo.groupNum}人团` : ''};
			showSharePopup.value = true;
		}
		
	}
</script>

<style lang="scss" scoped>
	.order-status-tabs {
		overflow: auto;
		white-space: nowrap;
		
		.tab-item {
			display: inline-flex;
			height: 30px;
			
			&:not(:last-child) {
				margin-right: 36px;
			}
		}
		.active {
			position: relative;
			
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 15%;
				height: 4px;
				width: 70%;
				border-radius: 4px;
				background: $uni-primary;
			}
		}
	}
</style>